package com.googlespeech.webapi.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ResourceBundle;

import org.springframework.stereotype.Service;

import com.googlespeech.webapi.service.GoogleSpeech;

@Service
public class GoogleSpeechImpl implements GoogleSpeech {

	@Override
	public byte[] getMp3FromText(String textInput) throws IOException {
		ResourceBundle bundle = ResourceBundle.getBundle("googleSpeechConfig");
		// TODO Auto-generated method stub
		
		URL url = null;
		int len;
		URLConnection conn = null;
		ByteArrayOutputStream outstream = new ByteArrayOutputStream();
		String tmpInput = textInput.replaceAll(" ", "%20");
		
		while(tmpInput.length() > 0){
			int rest = (tmpInput.length() >= 120)?120:tmpInput.length();
			String tmp = tmpInput.substring(0, rest);
			int lastSpaceIndex = tmp.lastIndexOf("%20");
			String chaine = tmpInput.substring(0, (rest >= 120)?lastSpaceIndex:tmpInput.length());
			tmpInput = tmpInput.substring(chaine.length());
			url = new URL(bundle.getString("google.speech.url") + chaine);
			
			conn = url.openConnection();
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB;     rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)");
			InputStream is = conn.getInputStream();
			
			byte[] buffer = new byte[4096];
	        while ((len = is.read(buffer)) > 0) {
	            outstream.write(buffer, 0, len);
	        }
	        conn = null;
	        is.close();
		}
		
		
		return outstream.toByteArray();
	}

}
